import os
import subprocess
import time
import webbrowser
import sys

def preview_nerf_model(config_path):
    # 验证配置文件
    if not os.path.exists(config_path):
        raise FileNotFoundError(f"配置文件不存在: {config_path}")
    
    print(f"准备预览模型: {config_path}")
    print("正在启动预览服务器...\n")

    # 解决Windows编码问题（核心）
    os.environ["PYTHONUTF8"] = "1"
    sys.stdout.reconfigure(encoding="utf-8")  # 强制标准输出为UTF-8

    # 构建预览命令（移除不支持的参数）
    preview_command = [
        "ns-viewer",
        "--load-config", config_path,
        "--viewer.websocket-port", "7007"  # 仅保留必要参数
    ]

    try:
        # 启动进程，禁用缓冲以实时输出
        process = subprocess.Popen(
            preview_command,
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT,
            text=True,
            bufsize=0,  # 无缓冲，实时输出
            shell=True,
            encoding="utf-8",
            errors="ignore"  # 忽略无法编码的字符
        )

        print("预览服务器日志:")
        viewer_url = "http://localhost:7007"
        # 自动打开浏览器（提前尝试，无需等待日志）
        webbrowser.open(viewer_url)
        print(f"\n已尝试打开浏览器: {viewer_url}")
        print("若未加载，等待服务器启动后刷新页面\n")

        # 实时打印日志（过滤特殊字符）
        for line in process.stdout:
            try:
                # 处理编码问题，确保中文正常显示
                print(line.strip())
            except UnicodeEncodeError:
                # 忽略无法打印的特殊字符
                pass

        # 保持进程运行
        while True:
            time.sleep(1)

    except KeyboardInterrupt:
        print("\n正在关闭预览服务器...")
        process.terminate()
        print("预览已结束")
    except Exception as e:
        print(f"\n发生错误: {str(e)}")
        if 'process' in locals():
            process.terminate()

if __name__ == "__main__":
    # 你的模型配置文件路径
    config_file_path = r"D:\train\south-building\results\nerfacto_2025-07-04_184436\nerfacto\2025-07-04_184442\config.yml"
    preview_nerf_model(config_file_path)